<template>
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    :loading="followLoading"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    :loading="followLoading"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'follow-user',
  model: {
    prop: 'isFollowed',
    event: 'update-is_followed'
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    // value: {
    //   type: Boolean,
    //   required: true
    // },
    followedId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      followLoading: false
    }
  },
  methods: {
    async onFollow() {
      this.followLoading = true
      try {
        if (this.isFollowed) {
          // 已关注,点击取消
          await deleteFollow(this.followedId)
        } else {
          // 未关注,点击关注
          await addFollow(this.followedId)
        }
        // 这里不能直接赋值进行修改,要传回父亲进行修改
        this.$emit('update-is_followed', !this.isFollowed)
        // this.$emit('input', !this.isFollowed)
      } catch (err) {
        let message = '操作失败'
        if (err.response && err.response.status === 400) {
          message = '你不能关注你自己'
        }
        this.$toast(message)
      }
      this.followLoading = false
    }
  }
}
</script>

<style></style>
